<template>
  <div class="highlight-container">
    <div class="highlight-content" ref="contentRef" v-html="highlightedText"></div>
  </div>
</template>

<script setup>
import { computed, nextTick, ref, watch } from 'vue'

const props = defineProps({
  text: {
    type: String,
    default: '',
  },
  keyword: {
    type: String,
    default: '',
  },
  currentMatchIndex: {
    type: Number,
    default: 0,
  },
})

// 添加一个响应式变量来强制更新
const updateKey = ref(0)
const contentRef = ref(null)

const emit = defineEmits(['match-count'])

// 计算高亮文本
const highlightedText = computed(() => {
  updateKey.value

  if (!props.keyword || !props.text) {
    emit('match-count', 0)
    return props.text
  }

  // 转义特殊字符，防止正则表达式错误
  const escapedKeyword = props.keyword.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
  const regex = new RegExp(`(${escapedKeyword})`, 'gi')

  // 计算匹配数量
  const matches = props.text.match(new RegExp(escapedKeyword, 'gi'))
  const count = matches ? matches.length : 0
  emit('match-count', count)

  // 高亮处理，为当前选中的匹配项添加特殊样式
  let matchIndex = 0
  return props.text.replace(regex, (match) => {
    matchIndex++
    const isCurrent = matchIndex === props.currentMatchIndex
    // 添加高亮类名( 当前高亮+普通高亮 || 普通高亮)
    const cls = isCurrent ? 'highlight current-highlight' : 'highlight'
    return `<span class="${cls}" data-match-index="${matchIndex}">${match}</span>`
  })
})

watch(
  () => props.currentMatchIndex,
  async (newVal, oldVal) => {
    // 强制 computed 重新计算（以防某些边界场景）
    updateKey.value++
    // 等待 DOM 更新后滚动到当前匹配项
    await nextTick()
    if (contentRef.value && newVal > 0) {
      const el = contentRef.value.querySelector('.current-highlight')
      if (el && typeof el.scrollIntoView === 'function') {
        el.scrollIntoView({ behavior: 'smooth', block: 'center', inline: 'nearest' })
      }
    }
  },
)
</script>

<style scoped lang="scss">
.highlight-container {
  margin: 20px 0;
  padding: 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  min-height: 100px;
  max-height: 500px;
  overflow-y: auto;

  .highlight-content {
    :deep(.highlight) {
      background-color: #fff3d4;
      color: #e6a23c;
      padding: 2px 4px;
      border-radius: 3px;
      font-weight: bold;
    }

    :deep(.current-highlight) {
      background-color: #ffd700;
      color: #333;
      padding: 2px 4px;
      border-radius: 3px;
      font-weight: bold;
      box-shadow: 0 0 0 2px #409eff;
    }
  }
}
</style>
